package com.yuan.pay_mall.vo;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.yuan.pay_mall.enums.ResponseEnum;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.validation.BindingResult;

import java.util.Objects;

/**
 * 返回给前端的对象，我们习惯称其为vo对象view Object
 * @param <T>
 */
@Data
@NoArgsConstructor
@JsonInclude(value=JsonInclude.Include.NON_NULL) /*json返回的值data为空不返回显示了*/
public class ResponseVo<T>{
    private Integer status;
    private String msg;
    private T data;

    public ResponseVo(Integer status, String msg) {
        this.status = status;
        this.msg = msg;
    }

    public ResponseVo(Integer status, T data) {
        this.status = status;
        this.data = data;
    }

    //成功的静态方法直接调用
    public static <T> ResponseVo<T> successByMessaage(String msg){
        return new ResponseVo<>(ResponseEnum.SUCCESS.getCode(),msg);
    }
    public static <T> ResponseVo<T> success(T data){
        return new ResponseVo<>(ResponseEnum.SUCCESS.getCode(),data);
    }
    public static <T> ResponseVo<T> success(){
        return new ResponseVo<>(ResponseEnum.SUCCESS.getCode(),ResponseEnum.SUCCESS.getDesc());
    }


    public static <T> ResponseVo<T> error(ResponseEnum ResponseEnum){
        return new ResponseVo<>(ResponseEnum.getCode(),ResponseEnum.getDesc());
    }
    public static <T> ResponseVo<T> error(ResponseEnum ResponseEnum,String msg){
        return new ResponseVo<>(ResponseEnum.getCode(),msg);
    }
    public static <T> ResponseVo<T> error(ResponseEnum ResponseEnum, BindingResult bindingResult){
        return new ResponseVo<>(ResponseEnum.getCode(),
                Objects.requireNonNull(bindingResult.getFieldError()).getField()+""
                        +bindingResult.getFieldError().getDefaultMessage());
        //上面，getFieldError()提示可能为空，自动提示加了个判断
    }
}


